package com.xncoding.pos.service;

import com.xncoding.pos.dynamic.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class JobService {

    @Autowired
    private ISysJobRepository jobRepository;
    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    public void save(SysJobPO job){
        SysJobPO save = jobRepository.save(job);
        if (job.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
            SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
            cronTaskRegistrar.addCronTask(task, job.getCron());
        }
    }

    public void update(SysJobPO sysJob){
        SysJobPO existedSysJob = jobRepository.findById(sysJob.getId()).get();
        jobRepository.save(sysJob);
        //先移除再添加
        if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
            SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
        }

        if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
            SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
            cronTaskRegistrar.addCronTask(task, sysJob.getCron());
        }
    }

    public void delete(Long id){
        SysJobPO existedSysJob = jobRepository.findById(id).get();
        jobRepository.deleteById(id);
        if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
            SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
        }
    }
}
